import re
def next_page(driver):
    """
    翻页
    """
    try:
        driver.find_element_by_link_text('Next').click()
        # driver.find_element_by_css_selector("#gs_n > center > table > tbody > tr > td:nth-child(12) > a > b").click()
        return True
    except:
        # print("Can't find next")
        return False

def wait_capcha(driver):
    data = driver.find_element_by_css_selector('body').text
    if 'not a robot' in data or '进行人机身份验证' in data:
        str = input("Please handle the capcha problem and press any key to continue")
        if str == 'q':
            quit
        return True
    return False

def get_current_page(driver):
    """
    获取当前页的文献信息
    """
    result = ""
    for i in range(1, 100):
        try:
            paper = driver.find_element_by_css_selector(f"#gs_res_ccl_mid > div:nth-child({i})")
        except:
            break
        text = paper.text
        text = '\n'.join([t for t in text.split('\n') if t[0] != "["])
        result += text + '\n\n'
    return result
    

def get_bibtext(driver, i):
    """
    获取当前页指定索引文献的bibtext
    """
    driver.find_element_by_css_selector(f"#gs_res_ccl_mid > div:nth-child({i}) > div.gs_ri > div.gs_fl > a.gs_or_cit.gs_nph > svg").click()

    # 第一个反应较慢，需要多次尝试
    while True:
        try:
            driver.find_element_by_css_selector("#gs_citi > a:nth-child(1)").click()
            break
        except:
            pass


    # 如果输入过验证码需要多返回一次
    if wait_capcha(driver):
        back_time = 3
    else:
        back_time = 2
    bibtext = driver.find_element_by_css_selector("body > pre").text
    for i in range(back_time):
        driver.back()
    return bibtext


def parse_bibtext(bibtext):
    """
    解析作者信息
    """
    # parse authors
    pattern = re.compile(r"author=\{(.+)\}")
    authors_str = pattern.search(bibtext).groups()[0]
    authors = authors_str.split('and')
    authors = [author.strip() for author in authors]

    # parse title
    pattern = re.compile(r"title=\{(.+)\}")
    title = pattern.search(bibtext).groups()[0]
    return {'authors': authors, 'title': title}


